const fs = require('node:fs');
const path = require('node:path');
const COS = require('cos-nodejs-sdk-v5');

console.log(process.env.CF_PAGES_BRANCH);
/*
if (process.env.CF_PAGES_BRANCH !== 'master') {
    console.log('Not master branch, skipping deploy');
    process.exit(0);
}
 */

if (process.env.CF_PAGES_BRANCH) {
  console.log('Not Gitlab CI, skipping deploy');
  process.exit(0);
}

const cosSecretId = 'AKIDCUrXH2X3GWqFjDnQ4ohbvT4fAc0GgGzl';
const cosSecretKey = 'wImIuV5eDqR1bJ0i1HUht6IPZis2Kaox';
const cosBucket = 'reecho-admin-dash-1253164967';
const cosRegion = 'ap-guangzhou';

const root = './dist';

const cos = new COS({
  SecretId: cosSecretId,
  SecretKey: cosSecretKey,
});

function getFilesList(dirPath) {
  const data = [];
  function getFiles(dirPath) {
    const filesList = fs.readdirSync(dirPath);
    for (let i = 0; i < filesList.length; i++) {
      const fileObj = {};
      fileObj.name = filesList[i];
      fileObj.path = path.join(dirPath, filesList[i]);
      let key = fileObj.path;
      key = key.split('/');
      key.shift();
      fileObj.key = key.join('/');
      const filePath = path.join(dirPath, filesList[i]);
      const stats = fs.statSync(filePath);
      if (stats.isDirectory()) {
        getFiles(filePath);
      } else {
        fileObj.type = path.extname(filesList[i]).substring(1);
        data.push(fileObj);
      }
    }
  }
  getFiles(dirPath);
  return data;
}

const files = getFilesList(root);
for (const file of files) {
  cos.putObject(
    {
      Bucket: cosBucket,
      Region: cosRegion,
      Key: file.key,
      Body: fs.createReadStream(file.path),
    },
    (err, data) => {
      if (err) {
        console.log(err);
      } else {
        console.log(`File Uploaded: ${file.path}`);
      }
    }
  );
}
